extends Node3D

# 可以把Grid和 Entities带的代码合到这里，方便统一操作
# 不过旋转层仍然需要通过脚本来提供额外参数，因此旋转层所带脚本需要保留

@onready var gridmap:GridMap = $GridMap
@onready var entities:Node3D = $Entities
@onready var player:CharacterBody3D = entities.get_node(^"Player")


#func _ready():
	#print(gridmap.owner == se

#ps：现在的旋转可能还是有点卡？（毕竟是逐个方块操作）
#func rotate_level_old(center:Vector3i, axis:Axis, hight:int, expand:int, times:int = 1):
	#var points = points_in_aabb(get_rotation_quarter(center,axis,hight,expand))
	#for point in points:
		#rotate_4cells(center,axis,point-center,times)

#新版本，就从这里改逻辑吧
func rotate_level(area:AABB, axis:Vector3i):
	
	#不锁定一下的话可能会视角抖动
	#好吧看来是无效代码
	#player.gravity_freeze = true
	
	# 选取有效点
	var valid_points:Array[Vector3i] = []
	for point in gridmap.get_used_cells():# 忽略空点 注意这里得到的是map坐标，要化成local坐标用
		if area.has_point(gridmap.map_to_local(point)):
			valid_points.append(point)
	# 记录单元格数据
	var cell_accounts:Array[Cell]=[]
	for point in valid_points:
		cell_accounts.append(Cell.gridmap_construct(point,gridmap))
		gridmap.set_cell_item(point,GridMap.INVALID_CELL_ITEM) # 清空以示“拿取”
	for cell in cell_accounts: # 每个cell作旋转处理
		cell.rotate(area.get_center(), axis)
		cell.apply(gridmap)
	
	#entity旋转
	entities.rotate_entities(area,axis)
	
	
